package com.guaju.yueshangLife.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.base.MyAppcomActivity;
import com.guaju.yueshangLife.bean.LoginBean;
import com.guaju.yueshangLife.databinding.ActivityRegistBinding;
import com.guaju.yueshangLife.event.CodeEvent;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.net.ApiClient;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.net.NetworkUtil;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.ToastUtil;
import com.guaju.yueshangLife.utils.Utils;
import com.guaju.yueshangLife.viewmodel.login.RegistVM;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class RegistActivity extends MyAppcomActivity {

    private ActivityRegistBinding binding;
    private String verify_key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_regist);
        //一体栏
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.home_background));
        RegistVM registVM = new RegistVM();
        binding.setViewmodel(registVM);
        initView();
    }

    private void initView() {
        binding.btNextStep.setEnabled(false);
        setListener();
    }

    private void setListener() {
        binding.tvGetcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendCode();
            }
        });
        binding.btNextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 先验证，验证通过跳转
                if (binding.cbReadLicence.isChecked()){
//                    跳转登录页面
                    if (!TextUtils.isEmpty(binding.etVerifycode.getText())){
                        ApiEntity.verifyCode(verify_key,binding.etVerifycode.getText().toString().trim());
                    }
                }else{
                    Toast.makeText(RegistActivity.this, "请先阅读并同意《月上生活馆服务协议》", Toast.LENGTH_SHORT).show();
                }


            }
        });
        binding.readLicence.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.cbReadLicence.isChecked()){
                    binding.cbReadLicence.setChecked(false);
                }
                else{
                    binding.cbReadLicence.setChecked(true);
                }
            }
        });

        binding.cbReadLicence.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b){
                    binding.btNextStep.setEnabled(true);
                    binding.btNextStep.setBackgroundResource(R.drawable.selector_login_button);
                }else {
                    binding.btNextStep.setBackgroundResource(R.drawable.shape_login_unable_bg);
                }
            }
        });

    }

    private void sendCode() {
        if (!NetworkUtil.isConnected(BaseApplication.getInstance())) {
            Toast.makeText(this, "网络连接异常", Toast.LENGTH_SHORT).show();
            return;
        }
        String mobile = binding.etPhonenum.getText().toString();
        if (Utils.isMobileNO(mobile)) {
            // 调用 发送验证码接口
            ApiEntity.getRegistCode(mobile);
        } else {
            ToastUtil.show("请输入正确手机号");
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CodeEvent event) {
        timer.start();
        String phone = event.getPhone();
        verify_key = event.getVerify_key();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginBean loginBean) {
        timer.start();
        LoginBean.DataBean data = loginBean.getData();
        if (data!=null){
            String access_token = data.getAccess_token();
            String token_type = data.getToken_type();
            PreferenceUtil.setToken(access_token);
            PreferenceUtil.setTokenType(token_type);
            PreferenceUtil.setIsLogin(true);
            Intent intent = new Intent(this, SetupPasswordActivity.class);
            startActivity(intent);
            finish();
        }
//        验证注册码
//        点击下一步
        //TODO 真正然后开始登录,暂时先跳转到登录页面
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            binding.tvGetcode.setText((millisUntilFinished / 1000) + "秒重发");
            binding.tvGetcode.setTextColor(getResources().getColor(R.color.c_gray2));
            binding.tvGetcode.setEnabled(false);
        }

        @Override
        public void onFinish() {
            binding.tvGetcode.setTextColor(Color.parseColor("#FF6C00"));
            binding.tvGetcode.setText("重新获取");
            binding.tvGetcode.setEnabled(true);
        }
    };

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ( keyCode == KeyEvent.KEYCODE_BACK ) {
//
//            }
//        return super.onKeyDown(keyCode, event);
//    }

}
